package com.orange.msm.controller;

import com.orange.commonutils.result.Result;
import com.orange.msm.service.MsmService;
import com.orange.msm.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author orange
 * @email orangestart@yeah.net
 * @create 2021-12-23 22:28
 * 使用邮箱发送验证码
 */
@RestController
@RequestMapping("/msmService/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送验证码
    @GetMapping("/send/{email}")
    public Result sendMsm(@PathVariable String email) {
        //从redis获取验证码，如果能获取，直接返回
        String code = redisTemplate.opsForValue().get(email);
        if (!StringUtils.isEmpty(code)) {
            //生命周期内发送同一验证码
            msmService.sendMsm(code, email);
            return Result.ok();
        }

        //获取不到，生成6位随机数
        code = RandomUtil.getSixBitRandom();

        //调用service中发送验证码
        boolean isSend = msmService.sendMsm(code, email);
        if (isSend) {
            //如果发送成功，把发送成功的code验证码保存到redis中，并设置有效时间，设置5分钟过期
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.error().message("验证码发送失败");
        }

    }

}
